﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using Universe.Computing.UCSharedLib;
using System.IO;
using System.ComponentModel;

namespace Universe.Computing.UCClientLib
{
    public class FileSender
    {
        private const int BufferSize=0x10000;
        public void SendJobLet(string fileName)
        {
            byte[] buffer = new byte[BufferSize];
            IPEndPoint ipEnd = new IPEndPoint(UCConfig.Instance.ServerIP, UCConfig.Instance.ServerPort);
            Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            clientSock.Connect(ipEnd);
            
            FileInfo fi = new FileInfo(fileName);
            int fileLength = (int)fi.Length;         
            
            int fileSendedCount=0;
            if (clientSock.Connected)
            {
                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

                NetworkStream ns=new NetworkStream(clientSock);
                byte[]fileLenBytes=BitConverter.GetBytes(fileLength);
                //write the file's length in bytes
                ns.Write(fileLenBytes, 0, fileLenBytes.Length);
                while(fileSendedCount<fileLength){
                //read one buffer
                int fileReadCount=fs.Read(buffer, fileSendedCount, buffer.Length);
                fileSendedCount += fileReadCount;
                ns.Write(buffer, 0, fileReadCount);
                }
                fs.Close();
                ns.Close();                
            }
            if (clientSock!=null&&clientSock.Connected)
            {
                clientSock.Close();
            }
        }
    }
}
